package com.codedef.diary;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.codedef.diary.config.HandlerInfo;
import com.codedef.diary.config.SharedConfig;
import com.codedef.diary.config.UrlConfig;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    private static final int LOGIN_SUCCESS = 1;

    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HandlerInfo.MAKE_TOAST:
                    Toast.makeText(LoginActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case LOGIN_SUCCESS:
                    Intent intent = new Intent(LoginActivity.this, DiaryListActivity.class);
                    startActivity(intent);
                    break;
            }
        }
    };

    private EditText usernameEdit;
    private EditText passwordEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initUi();
    }

    private void initUi() {
        usernameEdit = findViewById(R.id.edit_username);
        passwordEdit = findViewById(R.id.edit_password);
    }

    public void onLoginButtonClick(View view) {
        final String usernameString = usernameEdit.getText().toString();
        final String passwordString = passwordEdit.getText().toString();

        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = sendLoginRequest(usernameString, passwordString);
                System.out.println(UrlConfig.loginUrl);
                System.out.println(result);
                if("登录成功".equals(result)) {
                    Message message = new Message();
                    message.what = LOGIN_SUCCESS;
                    handler.sendMessage(message);
                } else if("无须再次登录".equals(result))  {
                    Message message = new Message();
                    message.what = LOGIN_SUCCESS;
                    handler.sendMessage(message);
                } else {
                    Message message = new Message();
                    message.what = HandlerInfo.MAKE_TOAST;
                    message.obj = "登录失败";
                    handler.sendMessage(message);
                }

            }
        }).start();


    }

    private String sendLoginRequest(String username, String password) {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("username", username)
                .add("password", password)
                .build();
        Request request = new Request.Builder()
                .url(UrlConfig.loginUrl)
                .post(requestBody)
                .build();
        Response response = null;
        String result = null;
        try {
            response = client.newCall(request).execute();
            result = response.body().string();
            if("登录成功".equals(result)) {
                String sessionId = response.header("Set-Cookie")
                        .substring(0, 43);
                //保存JSESSIONID
                SharedPreferences sp = getSharedPreferences(SharedConfig.SHARED_MODEL_NAME, Context.MODE_PRIVATE);
                sp.edit()
                        .putString(SharedConfig.KEY_SESSION, sessionId)
                        .apply();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}
